import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { login, getUserInfo, logout } from '@/api/user';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: Cookies.get('virtual_bank_token') || Cookies.get('token') || '',
    userInfo: null,
    loading: false,
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    username: (state) => state.userInfo?.username || '',
    realName: (state) => state.userInfo?.realName || '',
    avatar: (state) => state.userInfo?.avatar || '',
    balance: (state) => state.userInfo?.balance || 0,
  },
  
  actions: {
    // 设置token
    setToken(token) {
      this.token = token;
      // 将token存储到cookie中
      if (token) {
        // 使用与后端一致的cookie名称
        Cookies.set('virtual_bank_token', token, { expires: 7 }); // 7天过期
        // 为了兼容性同时也设置旧的cookie名称
        Cookies.set('token', token, { expires: 7 });
      } else {
        Cookies.remove('virtual_bank_token');
        Cookies.remove('token');
      }
    },
    
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
    },
    
    // 登录
    async loginAction(loginData) {
      try {
        this.loading = true;
        const res = await login(loginData);
        const { data } = res;
        
        // 设置token和用户信息
        this.setToken(data.token);
        this.setUserInfo(data);
        
        return Promise.resolve(res);
      } catch (error) {
        return Promise.reject(error);
      } finally {
        this.loading = false;
      }
    },
    
    // 获取用户信息
    async getUserInfoAction() {
      try {
        this.loading = true;
        const res = await getUserInfo();
        const { data } = res;
        
        // 设置用户信息
        this.setUserInfo(data);
        
        return Promise.resolve(res);
      } catch (error) {
        return Promise.reject(error);
      } finally {
        this.loading = false;
      }
    },
    
    // 处理登出
    async logoutAction() {
      try {
        this.loading = true;
        await logout();
        
        // 清除token和用户信息
        this.setToken('');
        this.setUserInfo(null);
        
        // 登出成功后刷新页面
        setTimeout(() => {
          window.location.href = '/login';
        }, 300);
        
        return Promise.resolve();
      } catch (error) {
        return Promise.reject(error);
      } finally {
        this.loading = false;
      }
    },
    
    // 重置状态
    resetState() {
      this.token = '';
      this.userInfo = null;
      Cookies.remove('virtual_bank_token');
      Cookies.remove('token');
    }
  }
});
